package com.codechuan.hallo_web.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.codechuan.hallo_web.entity.*;
import com.codechuan.hallo_web.mapper.*;
import com.codechuan.hallo_web.service.YkApiService;
import com.codechuan.hallo_web.utils.EncryptionUtil;
import com.codechuan.hallo_web.utils.RedisUtils;
import com.codechuan.hallo_web.utils.ResultUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

@Service
public class YkApiServiceImpl implements YkApiService {

    @Resource
    private SysUserAccountYkMapper sysUserAccountYkMapper;
    @Resource
    private SysKeyYkMapper sysKeyYkMapper;
    @Resource
    private SysAppUpdateMapper sysAppUpdateMapper;
    @Resource
    private SysUserConfigYkMapper sysUserConfigYkMapper;
    @Resource
    private SysUserTokenYkMapper sysUserTokenYkMapper;
    @Resource
    private SysCityMapper sysCityMapper;
    @Resource
    private SysUserOrderYkMapper sysUserOrderYkMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;


    /**
     * @param hashMap 数据
     * @Deprecated 月卡登陆
     */
    @Override
    public String ykLogin(HashMap<String, String> hashMap) {
        String account = hashMap.get("account");
        String keyNumber = hashMap.get("keyNumber");

        SysKeyYk sysKey = sysKeyYkMapper.selectByPrimaryKey(keyNumber);
        // 卡密一级校验
        if (sysKey == null) {
            return ResultUtils.success(null, "卡密不存在,或卡密错误!", 500);
        }
        // 卡密二级校验 是否封停
        if (sysKey.getStatus().equals("1")) {
            return ResultUtils.success(null, "激活码被封禁!", 500);
        }
        // 激活码三级校验 是否使用他人激活码
        if (sysKey.getPersonName() != null && !sysKey.getPersonName().equals(account)) {
            return ResultUtils.success(null, "该激活码非本人使用!", 500);
        }
        Date expirationTime = sysKey.getExpirationTime();
        // 激活码四级校验 是否到期和使用者校验
        if (sysKey.getExpirationTime() == null) {
            // 执行激活激活码判断类型加上对应的时间 激活码类型 0天卡 1周卡 2月卡 3测试卡
            Calendar calendar = Calendar.getInstance();
            switch (sysKey.getKeyTypes()) {
                case "0":
                    // 天卡逻辑
                    calendar.add(Calendar.DAY_OF_MONTH, 1);
                    sysKey.setExpirationTime(calendar.getTime());
                    break;
                case "1":
                    // 周卡逻辑
                    calendar.add(Calendar.DAY_OF_MONTH, 7);
                    sysKey.setExpirationTime(calendar.getTime());
                    break;
                case "2":
                    // 月卡逻辑
                    calendar.add(Calendar.DAY_OF_MONTH, 32);
                    sysKey.setExpirationTime(calendar.getTime());
                    break;
                case "3":
                    // 测试卡逻辑
                    calendar.add(Calendar.HOUR_OF_DAY, 5);
                    sysKey.setExpirationTime(calendar.getTime());
                    break;
            }
        }
        if (expirationTime != null) {
            // 校验用户是否到期
            if (sysKey.getExpirationTime().before(new Date())) {
                return ResultUtils.success(null, "您已到期!", 500);
            }
            // 判断用户是否为空 为空就是被解绑了重新赋值
            if (sysKey.getPersonName() == null) {
                sysKey.setPersonName(account);
                // 修改此激活码的使用者
                sysKeyYkMapper.updateByPrimaryKey(sysKey);
            }
        }else {
            // 第一次使用卡密设置卡密到期时间,和使用者
            sysKey.setPersonName(account);
            // 设置激活时间
            sysKey.setActivationTime(new Date());
            // 设置已激活
            sysKey.setIsActivated("1");
            // 修改卡密信息
            sysKey.setCreateTime(new Date());
            sysKeyYkMapper.updateByPrimaryKey(sysKey);
        }
        // 判断用户是否存在
        SysUserAccountYk sysUserAccountYk = sysUserAccountYkMapper.selectByPrimaryKey(account);
        // 判断用户是否封禁
        if (sysUserAccountYk != null && sysUserAccountYk.getAccountStatus().equals("1")) {
            return ResultUtils.success(null, "您已被封禁~", 500);
        }
        if (sysUserAccountYk == null) {
            // 保存用户到数据库
            SysUserAccountYk userAccountYk = new SysUserAccountYk();
            userAccountYk.setAccount(account);
            userAccountYk.setAccountStatus("0");
            sysUserAccountYkMapper.insert(userAccountYk);
        }

        Boolean b = stringRedisTemplate.opsForValue().getOperations().hasKey("LOGIN_YK_" + account);
        if (b == false) {
            RedisUtils.incrementKeyWithExpireTime(stringRedisTemplate, "LOGIN_YK_" + account);
        }
        // 查询版本号
        SysAppUpdate sysAppUpdate = sysAppUpdateMapper.selectByPrimaryKey("小叮当");
        return ResultUtils.success(sysAppUpdate.getVersion(), "success!", 200);
    }

    /**
     * @param hashMap 数据
     * @Deprecated 读取用户配置文件
     */
    @Override
    public String selectUserConfig(HashMap<String, String> hashMap) {
        ArrayList<SysUserConfigYk> sysUserConfigYk = sysUserConfigYkMapper.selectConfigList(hashMap.get("account"));
        if (!sysUserConfigYk.isEmpty()){
            return ResultUtils.success(JSONObject.toJSONString(sysUserConfigYk.get(0)), "success!", 200);
        }else {
            return ResultUtils.success("null", "success!", 200);
        }
    }

    /**
     * @param hashMap 数据
     * @Deprecated 读取用户小号
     */
    @Override
    public String selectUserMiniToken(HashMap<String, String> hashMap) {
        ArrayList<SysUserTokenYk> sysUserTokenYks = sysUserTokenYkMapper.selectAllTokenByAccount(hashMap.get("account"));
        HashMap<String, String> hashMap1 = new HashMap<>();
        hashMap1.put("data", JSONObject.toJSONString(sysUserTokenYks));
        return ResultUtils.success(JSONObject.toJSONString(hashMap1), "success!", 200);
    }

    /**
     * @param hashMap 数据
     * @Deprecated 获取主号信息
     */
    @Override
    public String getUserAccountInfo(HashMap<String, String> hashMap) {
        SysUserAccountYk sysUserAccountYk = sysUserAccountYkMapper.selectOnAccount(hashMap.get("account"));
        return ResultUtils.success(JSONObject.toJSONString(sysUserAccountYk), "success!", 200);
    }

    /**
     * @param hashMap 数据
     * @Deprecated 修改主号信息
     */
    @Override
    public String updateAccountToken(HashMap<String, String> hashMap) {
        String token = hashMap.get("token");
        String ticket = hashMap.get("ticket");
        String account = hashMap.get("account");
        int i = sysUserAccountYkMapper.updateAccountToken(token, ticket, account);
        return ResultUtils.success(String.valueOf(i), "success!", 200);
    }

    /**
     * @param hashMap 数据
     * @Deprecated 保存用户配置文件
     */
    @Override
    @Transactional
    public String saveUserConfig(HashMap<String, String> hashMap) {
        String data = hashMap.get("data");
        JSONObject jsonObject = JSONObject.parseObject(data);

        SysUserConfigYk sysUserConfigYk = new SysUserConfigYk();
        sysUserConfigYk.setStartaddress(jsonObject.getString("startAddress"));
        sysUserConfigYk.setSdtype(jsonObject.getString("sdType"));
        sysUserConfigYk.setPxtype(jsonObject.getString("pxType"));
        sysUserConfigYk.setNotimecheck(jsonObject.getString("noTimeCheck"));
        sysUserConfigYk.setJttimecheck(jsonObject.getString("jtTimeCheck"));
        sysUserConfigYk.setMttimecheck(jsonObject.getString("mtTimeCheck"));
        sysUserConfigYk.setHttimecheck(jsonObject.getString("htTimeCheck"));

        sysUserConfigYk.setStarttime(jsonObject.getString("startTime"));
        sysUserConfigYk.setEndtime(jsonObject.getString("endTime"));
        sysUserConfigYk.setPccitycheck(jsonObject.getString("pcCityCheck"));
        sysUserConfigYk.setPccitytext(jsonObject.getString("pcCityText"));

        sysUserConfigYk.setZdcitycheck(jsonObject.getString("zdCityCheck"));
        sysUserConfigYk.setZdcitytext(jsonObject.getString("zdCityText"));
        sysUserConfigYk.setPccheck(jsonObject.getString("pcCheck"));
        sysUserConfigYk.setPcminiperson(jsonObject.getInteger("pcMiniPerson"));
        sysUserConfigYk.setPcmaxperson(jsonObject.getInteger("pcMaxPerson"));

        sysUserConfigYk.setDxcheck(jsonObject.getString("dxCheck"));
        sysUserConfigYk.setDxminiperson(jsonObject.getInteger("dxMiniPerson"));
        sysUserConfigYk.setDxmaxperson(jsonObject.getInteger("dxMaxPerson"));

        sysUserConfigYk.setSscheck(jsonObject.getString("ssCheck"));
        sysUserConfigYk.setSsminiperson(jsonObject.getInteger("ssMiniPerson"));
        sysUserConfigYk.setSsmaxperson(jsonObject.getInteger("ssMaxPerson"));

        sysUserConfigYk.setZjdxcheck(jsonObject.getString("zjDxCheck"));
        sysUserConfigYk.setYdgscheck(jsonObject.getString("ydGsCheck"));
        sysUserConfigYk.setPcthcheck(jsonObject.getString("pcThCheck"));

        sysUserConfigYk.setMinimoney(jsonObject.getInteger("miniMoney"));
        sysUserConfigYk.setMaxmoney(jsonObject.getInteger("maxMoney"));
        sysUserConfigYk.setCkjl(jsonObject.getInteger("ckJl"));
        sysUserConfigYk.setSxnumber(jsonObject.getInteger("sxNumber"));
        sysUserConfigYk.setAccount(jsonObject.getString("account"));
        // 先删除
        sysUserConfigYkMapper.deleteByPrimaryKey(jsonObject.getString("account"));
        sysUserConfigYkMapper.insert(sysUserConfigYk);
        return ResultUtils.success(null, "success!", 200);
    }

    /**
     * @param hashMap 数据
     * @Deprecated 修改用户主号token状态
     */
    @Override
    public String updateAccountTokenStatus(HashMap<String, String> hashMap) {
        sysUserAccountYkMapper.updateAccountTokenStatus(hashMap.get("account"));
        return ResultUtils.success(null, "success!", 200);
    }

    /**
     * @param hashMap 数据
     * @Deprecated 修改用户小号token状态
     */
    @Override
    public String updateMiniTokenStatus(HashMap<String, String> hashMap) {
        sysUserTokenYkMapper.updateMiniTokenStatus(hashMap.get("token"));
        return ResultUtils.success(null, "success!", 200);
    }

    /**
     * @param hashMap 数据
     * @Deprecated 获取指定城市编码
     */
    @Override
    public String selectZdCsCityCode(HashMap<String, String> hashMap) {
        StringBuilder stringBuilder = new StringBuilder();
        String cityName = hashMap.get("cityName");
        if (cityName.contains(",")) {
            String[] split = cityName.split(",");
            for (String name : split) {
                String cityCode = sysCityMapper.selectCodeByCityName(name);
                stringBuilder.append(cityCode).append(",");
            }
        } else {
            String cityCode = sysCityMapper.selectCodeByCityName(cityName);
            stringBuilder.append(cityCode);
        }

        try {
            return ResultUtils.success(stringBuilder.toString(), "success", 200);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param hashMap 数据
     * @Deprecated 添加用户小号
     */
    @Override
    public String addMiniToken(HashMap<String, String> hashMap) {
        String token = hashMap.get("token");
        String ticket = hashMap.get("ticket");
        String phone = hashMap.get("phone");
        String account = hashMap.get("account");
        SysUserTokenYk sysUserTokenYk = new SysUserTokenYk();
        sysUserTokenYk.setToken(token);
        sysUserTokenYk.setTicket(ticket);
        sysUserTokenYk.setPhone(phone);
        sysUserTokenYk.setAccount(account);
        sysUserTokenYk.setStatus("0");
        int insert = sysUserTokenYkMapper.insert(sysUserTokenYk);
        try {
            return ResultUtils.success(String.valueOf(insert), "success", 200);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param hashMap 数据
     * @Deprecated 删除用户小号
     */
    @Override
    public String deleteUserMiniToken(HashMap<String, String> hashMap) {
        int i = sysUserTokenYkMapper.deleteByPrimaryKey(hashMap.get("token"));
        try {
            return ResultUtils.success(String.valueOf(i), "success", 200);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param hashMap 数据
     * @Deprecated 添加用户订单
     */
    @Override
    public String addUserOrder(HashMap<String, String> hashMap) {
        JSONObject jsonObject = JSONObject.parseObject(hashMap.get("data"));
        SysUserOrderYk sysUserOrderYk = new SysUserOrderYk();
        sysUserOrderYk.setDriverjourneyguid(jsonObject.getString("driverJourneyGuid"));
        sysUserOrderYk.setPaxjourneyguid(jsonObject.getString("paxJourneyGuid"));
        sysUserOrderYk.setPrice(jsonObject.getString("price"));
        sysUserOrderYk.setPersonnumber(jsonObject.getString("personNumber"));
        sysUserOrderYk.setOrderdes(jsonObject.getString("orderDes"));
        sysUserOrderYk.setCarpooltext(jsonObject.getString("carPoolText"));
        sysUserOrderYk.setCreatetime(new Date());
        sysUserOrderYk.setAccount(jsonObject.getString("account"));
        sysUserOrderYk.setMsg(jsonObject.getString("msg"));
        sysUserOrderYk.setStartaddress(jsonObject.getString("startAddress"));
        sysUserOrderYk.setEndaddress(jsonObject.getString("endAddress"));
        sysUserOrderYk.setStartdes(jsonObject.getString("startDes"));
        int i = sysUserOrderYkMapper.insertSelective(sysUserOrderYk);
        try {
            return ResultUtils.success(String.valueOf(i), "success", 200);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param hashMap 数据
     * @Deprecated 删除所有用户订单
     */
    @Override
    public String deleteOrderInfo(HashMap<String, String> hashMap) {
        sysUserOrderYkMapper.deleteOrderInfo(hashMap.get("account"));
        try {
            return ResultUtils.success(null, "success", 200);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param hashMap 数据
     * @Deprecated 查询所有用户订单
     */
    @Override
    public String selectUserOrderListByAccount(HashMap<String, String> hashMap) {
        ArrayList<SysUserOrderYk> selectUserOrderListByAccount = sysUserOrderYkMapper.selectUserOrderListByAccount(hashMap.get("account"));
        HashMap<String, String> data = new HashMap<>();
        data.put("data", JSONObject.toJSONString(selectUserOrderListByAccount));
        try {
            return ResultUtils.success(JSONObject.toJSONString(data), "success", 200);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param hashMap 数据
     * @Deprecated 解绑月卡
     */
    @Override
    public String ykNoBind(HashMap<String, String> hashMap) {
        String keyNumber = hashMap.get("keyNumber");
        // 通过BL + 账号获取次数
        Boolean b = stringRedisTemplate.opsForValue().getOperations().hasKey("XDD_" + keyNumber);
        if (b) {
            // 获取解绑次数
            String noBindNumber = stringRedisTemplate.opsForValue().get("XDD_" + keyNumber);
            Integer i = Integer.valueOf(noBindNumber);
            if (i > 5) {
                return ResultUtils.success("1", "本周解绑次数已满!", 500);
            } else {
                RedisUtils.incrementKeyWithExpireTime(stringRedisTemplate, "XDD_" + keyNumber);
                // 解绑账号机器吗
                sysKeyYkMapper.noBind(keyNumber);
                return ResultUtils.success("1", "解绑成功,请重新登陆~", 200);

            }
        } else {
            RedisUtils.incrementKeyWithExpireTime(stringRedisTemplate, "XDD_" + keyNumber);
            // 解绑账号机器吗
            sysKeyYkMapper.noBind(keyNumber);
            return ResultUtils.success("1", "解绑成功,请重新登陆~", 200);
        }
    }
}
